package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.PageInfo;
import com.tanhua.common.mapper.SettingsMapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.Announcement;
import com.tanhua.common.pojo.Settings;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class IMService {

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private QuanZiApi quanZiApi;

    @Autowired
    private AnnouncementService announcementService;

    @Autowired
    private BlackUserService blackUserService;

    @Autowired
    private SettingsMapper settingsMapper;

    //根据环信用户名查询用户信息
    public UserInfoVo queryUserInfoByUserName(String userName) {
        //查询环信账户
        HuanXinUser huanXinUser = this.huanXinApi.queryUserByUserName(userName);
        if (ObjectUtil.isEmpty(huanXinUser)) {
            return null;
        }

        //查询用户信息
        UserInfo userInfo = userInfoMapper.selectById(huanXinUser.getUserId());
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);

        return userInfoVo;
    }

    //添加好友
    public boolean contactUser(Long friendId) {
        User user = UserThreadLocal.get();

        String id = this.usersApi.saveUsers(user.getId(), friendId);

        if (StrUtil.isNotEmpty(id)) {
            //注册好友关系到环信
            return this.huanXinApi.addUserFriend(user.getId(), friendId);
        }

        return false;
    }

    //查看好友列表
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();

        List<Users> usersList;
        if (StringUtils.isNotEmpty(keyword)) {
            //关键不为空，查询所有的好友，在后面进行关键字过滤
            usersList = this.usersApi.queryAllUsersList(user.getId());
        } else {
            //关键字为空，进行分页查询
            usersList = this.usersApi.queryUsersList(user.getId(), page, pageSize);
        }

        if (CollUtil.isEmpty(usersList)) {
            return pageResult;
        }

        List<Object> userIds = CollUtil.getFieldValues(usersList, "friendId");

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.like("nick_name", keyword);
        }

        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);

        List<UsersVo> contactsList = new ArrayList<>();
        //填充用户信息
        for (UserInfo userInfo : userInfoList) {
            UsersVo usersVo = new UsersVo();
            usersVo.setId(userInfo.getUserId());
            usersVo.setAge(userInfo.getAge());
            usersVo.setAvatar(userInfo.getLogo());
            usersVo.setGender(userInfo.getSex().name().toLowerCase());
            usersVo.setNickname(userInfo.getNickName());
            //环信用户账号
            usersVo.setUserId("HX_" + String.valueOf(userInfo.getUserId()));
            usersVo.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));
            contactsList.add(usersVo);
        }

        pageResult.setItems(contactsList);
        return pageResult;
    }

    //查询消息点赞列表
    public PageResult queryLikeCommentList(Integer page, Integer pageSize) {
        //1.解析token
        User user = UserThreadLocal.get();

        //2.查看该用户的点赞消息
        List<Comment> commentList = this.quanZiApi.queryLikeCommentListByUser(user.getId(), page, pageSize);
        //3.调用复制方法
        return this.fillUserCommentList(commentList, page, pageSize);
    }

    //查询消息喜欢列表
    public PageResult queryLoveCommentList(Integer page, Integer pageSize) {
        //1.解析token
        User user = UserThreadLocal.get();

        //查询用户点赞通知是否开启
        LambdaUpdateWrapper<Settings> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Settings::getUserId, user.getId());
        Settings settings = settingsMapper.selectOne(wrapper);
        if (ObjectUtil.isEmpty(settings) || settings.getLikeNotification() != 1) {
            return null;
        }

        //2.查看该用户的喜欢消息
        List<Comment> commentList = this.quanZiApi.queryCommentListByUser(user.getId(), page, pageSize);
        //3.调用复制方法
        return this.fillUserCommentList(commentList, page, pageSize);
    }

    //查询消息评论列表
    public PageResult queryUserCommentList(Integer page, Integer pageSize) {
        //1.解析token
        User user = UserThreadLocal.get();

        //查询用户点赞通知是否开启
        LambdaUpdateWrapper<Settings> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Settings::getUserId, user.getId());
        Settings settings = settingsMapper.selectOne(wrapper);
        if (ObjectUtil.isEmpty(settings) || settings.getPinglunNotification() != 1) {
            return null;
        }
        //2.查看该用户的评论消息
        List<Comment> commentList = this.quanZiApi.queryCommentListByUser(user.getId(), page, pageSize);
       //3.调用复制方法
       return this.fillUserCommentList(commentList, page, pageSize);
    }

    //复制
    private PageResult fillUserCommentList(List<Comment> commentList,Integer page, Integer pageSize){
        //1.封装响应结果集合
        List<MessageCommentVo> list = new ArrayList<>();
        //2.遍历查询到的结果
        for (Comment comment : commentList) {
            //加入黑名单过滤
            List<Long> blacks = blackUserService.queryAllBlackUser();
            //如果是黑名单中的用户的评论点赞 则不封装
            if(!blacks.contains(comment.getUserId())){
                //3.新建响应结果
                MessageCommentVo messageCommentVo = new MessageCommentVo();
                messageCommentVo.setId(comment.getId().toHexString());
                messageCommentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "yyyy-MM-dd HH:mm"));
                //4.根据用户id查询userInfo
                LambdaUpdateWrapper<UserInfo> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(UserInfo::getUserId, comment.getUserId());
                UserInfo userInfo = userInfoMapper.selectOne(wrapper);
                //非空判断
                if (ObjectUtil.isNotEmpty(userInfo)){
                    messageCommentVo.setAvatar(userInfo.getLogo());
                    messageCommentVo.setNickname(userInfo.getNickName());
                    //5.添加到响应结果集合
                    list.add(messageCommentVo);
                }
            }
            /*//3.新建响应结果
            MessageCommentVo messageCommentVo = new MessageCommentVo();
            messageCommentVo.setId(comment.getId().toHexString());
            messageCommentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "yyyy-MM-dd HH:mm"));
            //4.根据用户id查询userInfo
            LambdaUpdateWrapper<UserInfo> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(UserInfo::getUserId, comment.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            messageCommentVo.setAvatar(userInfo.getLogo());
            messageCommentVo.setNickname(userInfo.getNickName());
            //5.添加到响应结果集合
            list.add(messageCommentVo);*/
        }
        //6.封装返回前端的对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(list);
        return pageResult;
    }

    //查询公告列表
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {

        IPage<Announcement> announcementPage = this.announcementService.queryList(page, pageSize);

        List<AnnouncementVo> announcementVoList = new ArrayList<>();

        for (Announcement record : announcementPage.getRecords()) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(record.getId().toString());
            announcementVo.setTitle(record.getTitle());
            announcementVo.setDescription(record.getDescription());
            announcementVo.setCreateDate(DateUtil.format(record.getCreated(), "yyyy-MM-dd HH:mm"));

            announcementVoList.add(announcementVo);
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(announcementVoList);

        return pageResult;
    }
}
